package sedh.project
import grails.plugins.springsecurity.Secured;

class UserController {

	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	def springSecurityService
	
	def index = {
		redirect(action: "create", params: params)
	}
	
	@Secured(['ROLE_ADMIN', 'IS_AUTHENTICATED_REMEMBERED'])
	def create = {
		def userInstance = new User()
		userInstance.properties = params
		return [userInstance: userInstance]
	}
	
	@Secured(['ROLE_ADMIN', 'IS_AUTHENTICATED_REMEMBERED'])
	def list = {
		params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
		[ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]
	}
	
	@Secured(['ROLE_ADMIN', 'IS_AUTHENTICATED_REMEMBERED'])
	def show = {
		def userInstance = User.get( params.id )

		if(!userInstance) {
			flash.message = "Usuario nao encontrado com o id ${params.id}"
			redirect(action:list)
		}
		else {
			return [ userInstance : userInstance ]
		}
	}

	def save = {
		def userInstance = new User(params)
		userInstance.enabled = true
		if(!userInstance.hasErrors() && userInstance.save()) {
			flash.message = "Usuario ${userInstance.id} criado"
			redirect(action:show,id:userInstance.id)
		}
		else {
			render(view:'create',model:[userInstance:userInstance])
		}
	}
	@Secured(['IS_AUTHENTICATED_REMEMBERED'])
	def edit = {
		def userInstance = currentUser
		
		if(!userInstance) {
			flash.message = "Usuario com id ${params.id} nao encontrado"
			redirect(action:list)
		}
		else {
			return [ userInstance : userInstance ]
		}
	}

	def update = {
		def userInstance = User.get( params.id )
		if(userInstance) {
			if(params.version) {
				def version = params.version.toLong()
				if(userInstance.version > version) {

					userInstance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing.")
					render(view:'edit',model:[userInstance:userInstance])
					return
				}
			}
			userInstance.properties = params
			if(!userInstance.hasErrors() && userInstance.save()) {
				flash.message = "Usuario ${params.id} atualizado"
				redirect(action:show,id:userInstance.id)
			}
			else {
				render(view:'edit',model:[userInstance:userInstance])
			}
		}
		else {
			flash.message = "Usuario nao encontrado com o id ${params.id}"
			redirect(action:list)
		}
	}
	
	@Secured(['ROLE_ADMIN', 'IS_AUTHENTICATED_REMEMBERED'])
	def delete = {
		def userInstance = User.get( params.id )
		if(userInstance) {
			try {
				userInstance.delete(flush:true)
				flash.message = "Usuario ${params.id} deletado"
				redirect(action:list)
			}
			catch(org.springframework.dao.DataIntegrityViolationException e) {
				flash.message = "Usuario ${params.id} nao pode ser deletado"
				redirect(action:show,id:params.id)
			}
		}
		else {
			flash.message = "Usuario com id ${params.id} nao encontrado"
			redirect(action:list)
		}
	}
	
	private getCurrentUser() {
		return User.get(springSecurityService.principal.id)
	}
}
